package designMode.创建型模式;

public class Singletion {
/**
 * 单例模式是一种创建型设计模式， 让你能够保证一个类只有一个实例， 并提供一个访问该实例的全局节点。
 *
 *
 *
 */

}



//饿汉式
final class HungrySingletion {
    //类初始化时，立即加载这个对象，加载时线程安全
    private static HungrySingletion instance =new HungrySingletion();
    //私有化构造器，外部不能调用
    private HungrySingletion() {}
    //方法没有同步，调用效率高
    public static HungrySingletion getInstance() {
        return instance;
    }
}

//线程安全懒汉式
class SingletonDemo2 {
    private SingletonDemo2() {}
    private static SingletonDemo2 singletonDemo2;
    public synchronized static SingletonDemo2 getInstance() {
        if (singletonDemo2 == null) {
            singletonDemo2 = new SingletonDemo2();
        }
        return singletonDemo2;
    }
}

//双重检查锁方式(禁止代码重排序)
class SingletonDemo3 {
    private SingletonDemo3() {}
    private static volatile SingletonDemo4 singletonDemo4;

}

//静态内部类
class SingletonDemo4 {
    private SingletonDemo4() {}
    private static class SingletonHolder {
        private static final SingletonDemo4 singletonDemo4= new SingletonDemo4();
    }
    public static SingletonDemo4 getInstance() {
        return SingletonHolder.singletonDemo4;
    }
}



